﻿package net.wangit.framework.util;

import net.wangit.MapList;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.framework.config.DebugSettings;
import net.wangit.framework.session.AgileSession;
import net.wangit.framework.session.UnitDataHelper;
import net.wangit.support.MapListFactory;
import net.wangit.util.Checker;
import net.wangit.util.ClassUtil;
import net.wangit.view.enumeration.EnumerationDataMode;
import net.wangit.view.unit.UnitComponent;
import net.wangit.view.unit.UnitConfigurationException;
import net.wangit.view.unit.util.UnitUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class DataProcessor {
	private static Log log = LogFactory.getLog(DataProcessor.class);

	public static void loadData(ActionContext ac, UnitComponent uc) {
		AgileSession session = ActionContextHelper.getSession(ac);
		MapList snapshot = session.getSnapshot(uc);

		if (snapshot != null) {
			if (DebugSettings.isDebugEnabled(log, uc)) {
				log.debug("load data from snapshot: " + UnitUtil.getUrl(uc));
			}
			uc.setData(snapshot);
		} else if (uc.isRemember()) {
			if (DebugSettings.isDebugEnabled(log, uc)) {
				log.debug("load data from memory: " + UnitUtil.getUrl(uc));
			}
			uc.setData(UnitDataHelper.getMemoryData(uc));
		} else if (!("a".equals(uc.getShowMode()))) {
			if (DebugSettings.isDebugEnabled(log, uc)) {
				log.debug("load data by config: " + UnitUtil.getUrl(uc));
			}
			loadDataAuto(ac, uc);
		}
	}

	private static void loadDataAuto(ActionContext ac, UnitComponent uc) {
		String dataExpression = uc.getDataExpression();
		if (Checker.isEmpty(dataExpression)) {
			return;
		}
		int dataMode = uc.getDataMode();
		switch (dataMode) {
		case EnumerationDataMode.SQL_PROVIDER:
		case EnumerationDataMode.SQL:
			try {
				UnitDataUtil.loadDataFromDatabase(ac, uc);
			} catch (Exception e) {
				throw new UnitConfigurationException("load data error(SQL):"
						+ UnitUtil.getUrl(uc), e);
			}
			break;
		case EnumerationDataMode.MAPLIST:
			try {
				MapListFactory factory = (MapListFactory) ClassUtil.loadClass(
						dataExpression).newInstance();
				uc.setData(factory.getMapList());
			} catch (Exception e) {
				throw new UnitConfigurationException(
						"load data error(MapListFactory):"
								+ UnitUtil.getUrl(uc), e);
			}
			break;
		case EnumerationDataMode.STATIC:
			try {
				uc.setData(MapListUtil.getMapList(dataExpression));
			} catch (Exception e) {
				throw new UnitConfigurationException("load data error(Static):"
						+ UnitUtil.getUrl(uc), e);
			}
			break;
		}
	}
}